package com.team.childapp.ui.ai

import android.Manifest
import android.annotation.SuppressLint
import android.media.AudioManager
import android.os.Handler
import com.bytedance.speech.speechengine.SpeechEngine
import com.team.childapp.R
import com.team.childapp.base.activity.BaseActivity
import com.team.childapp.bean.ai.AIHelperHistoryBean
import com.team.childapp.databinding.ActivityAiGeneratePictureByImageBinding
import com.team.childapp.ui.ai.adapter.AiGeneratePictureByImageAdapter
import com.team.childapp.util.speechUtils.SpeechStreamRecorder

class AiGeneratePictureByImageActivity : BaseActivity<ActivityAiGeneratePictureByImageBinding>(R.layout.activity_ai_generate_picture_by_image) {

    private var selectImagePath: String? = null
    private var aiMessageAdapter: AiGeneratePictureByImageAdapter? = null
    private var dataList: MutableList<AIHelperHistoryBean>? = null


    // Paths
    private var mDebugPath = ""
    private var pageNum = 1
    private var pageSize: kotlin.Int = 10
    private val map: Map<String, AIHelperHistoryBean> = HashMap<String, AIHelperHistoryBean>()
    private var openSound = true

    private var mStreamRecorder: SpeechStreamRecorder? = null
    private var mSpeechEngine: SpeechEngine? = null
    private var recordIsRunning = false
    private var mFinishTalkingTimestamp: Long = -1
    private var recordRunnable: Runnable? = null
    private var recordHandler: Handler? = null
    private var mAudioManager: AudioManager? = null
    private  val ASR_PERMISSIONS = listOf(
                Manifest.permission.RECORD_AUDIO
            )


    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {
        /*SpeechEngineGenerator.PrepareEnvironment(getApplicationContext(), getApplication())
        if (mDebugPath.isEmpty()) {
            mDebugPath = getDebugPath()
        }
        Log.i("SpeechDemo", "当前调试路径：$mDebugPath")
        dataList = ArrayList<AIHelperHistoryBean>()
        val linearLayoutManager = LinearLayoutManager(this)
        recyclerView!!.layoutManager = linearLayoutManager
        aiMessageAdapter = AiGeneratePictureByImageAdapter(this)
        aiMessageAdapter.setOnItemClick(object : onItemClick() {
            override fun onClickView(bean: AIHelperHistoryBean, view: View?) {
                PreviewDialog.showDialog(getSupportFragmentManager(), bean.getImageUrl(), true)
            }
        })
        recyclerView.adapter = aiMessageAdapter
        aiMessageAdapter.setData(dataList)

        if (mStreamRecorder == null) {
            mStreamRecorder = SpeechStreamRecorder()
        }

        tv_play2!!.setOnTouchListener { v: View?, event: MotionEvent ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                Glide.with(this)
                    .asGif()
                    .load(R.mipmap.icon_speach)
                    .into(playImage)
                playImage!!.visibility = View.VISIBLE
                tv_play2.visibility = View.GONE
                recordBtnTouchDown()
                return@setOnTouchListener true
            } else if (event.action == MotionEvent.ACTION_UP) {
                playImage!!.visibility = View.GONE
                tv_play2.visibility = View.VISIBLE
                recordBtnTouchUp()
                return@setOnTouchListener true
            } else if (event.action == MotionEvent.ACTION_CANCEL) {
                playImage!!.visibility = View.GONE
                tv_play2.visibility = View.VISIBLE
                recordBtnTouchUp()
                return@setOnTouchListener true
            }
            false
        }
        mAudioManager = getApplicationContext().getSystemService(Context.AUDIO_SERVICE)
        tv_play2.postDelayed({ initEngine() }, 1000)

        val serviceIntent: Intent = Intent(this, ForegroundService::class.java)
        serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android")
        ContextCompat.startForegroundService(this, serviceIntent)
        et_show!!.setOnEditorActionListener(OnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEND) {
                if (TextUtils.isEmpty(selectImagePath)) {
                    ToastUtil.showShort("请先选择图片")
                    return@OnEditorActionListener false
                }
                input!!.visibility = View.GONE
                closekeyboard()
                setMyResult(et_show.text.toString())
                et_show.setText("")
            }
            false
        })

        getData(true)
        swp!!.setOnRefreshListener { getData(false) }
        SoftKeyBoardListener.setListener(this, object : OnSoftKeyBoardChangeListener() {
            override fun keyBoardShow(height: Int) {
                if (input!!.visibility == View.VISIBLE) {
                    return
                }
                input.visibility = View.VISIBLE
                val constraintSet = ConstraintSet()
                constraintSet.clone(constraintLayout)
                constraintSet.connect(
                    input.id,
                    ConstraintSet.BOTTOM,
                    ConstraintSet.PARENT_ID,
                    ConstraintSet.BOTTOM,
                    height
                )
                constraintLayout!!.requestLayout()
                constraintSet.applyTo(constraintLayout)
                et_show.requestFocus()
                // mPopupWindow.showAtLocation(decorView, Gravity.BOTTOM, 0, height);
            }

            override fun keyBoardHide(height: Int) {
                input!!.visibility = View.GONE
                //  mPopupWindow.dismiss();
            }
        })
        et_show.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
            }

            override fun afterTextChanged(editable: Editable) {
                et_send!!.setText(editable.toString())
            }
        })*/
    }

    override fun initData() {
    }


    fun getData(isRfresh: Boolean) {
        if (isRfresh) {
            pageNum = 1
            dataList!!.clear()
        } else {
            pageNum++
        }
       /* AIMessageLogical.getInstance().requestAIHistory(
            this,
            pageNum.toString(),
            pageSize.toString(),
            "5",
            object : ICallBackResultListener() {
                override fun onCallBack(result: Any?) {
                    if (result != null) {
                        val helperHistoryBean: AIHelperHistoryBean = result as AIHelperHistoryBean
                        if (helperHistoryBean.rows != null && helperHistoryBean.rows.size() > 0) {
                            Collections.reverse(helperHistoryBean.rows)
                            dataList!!.addAll(0, helperHistoryBean.rows)
                            aiMessageAdapter.notifyDataSetChanged()
                            if (pageNum == 1) {
                                recyclerView!!.scrollToPosition(dataList!!.size - 1)
                            }
                        }
                    } else {
                        if (!isRfresh) {
                            pageNum--
                        }
                    }
                    swp!!.isRefreshing = false
                }
            })*/
    }
}